package com.lemon.smartsafety.ui.activity.voice;

import android.Manifest;
import android.app.Dialog;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.lemon.smartsafety.BuildConfig;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppManager;
import com.lemon.smartsafety.app.AppService;
import com.lemon.smartsafety.app.IApplication;
import com.lemon.smartsafety.entity.event.evidence.VoiceEvent;
import com.lemon.smartsafetynew.ui.activity.base.LemonPermissionListener;
import com.lemon.smartsafetynew.ui.activity.base.SwipeBackActivity;
import com.lemon.smartsafety.utils.common.FileUtil;
import com.lemon.smartsafety.utils.common.StringUtils;

import java.io.IOException;
import java.util.ArrayList;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * Created by Cooliean on 16/4/12.
 * 录音
 */
public class RecordVoiceActivity extends SwipeBackActivity {

    @Bind(R.id.btn_play)
    Button   btnPlay;
    @Bind(R.id.btn_record)
    Button   btnRecord;
    @Bind(R.id.btn_submit)
    Button   btnSubmit;
    @Bind(R.id.btn_cancel)
    Button   btnCancel;
    @Bind(R.id.tv_record_time)
    TextView tvRecordTime;
    @Bind(R.id.tv_file_url)
    TextView tvFileUrl;


    private TextView  mTvDialogRecordTxt;
    private ImageView mIvDialogRecVolume;


    // private static final int MAX_RECORD_TIME = 30; // 最长录制时间，单位秒，0为无时间限制
    private static final int MIN_RECORD_TIME = 1; // 最短录制时间，单位秒，0为无时间限制

    private static final int    RECORD_OFF = 0; // 不在录音
    private static final int    RECORD_ON  = 1; // 正在录音
    private              String mFileUrl   = "";// 录音文件名


    private int     recordState = 0; // 录音状态
    private float   recodeTime  = 0.0f; // 录音时长
    private double  voiceValue  = 0.0; // 录音的音量值
    private boolean playState   = false; // 录音的播放状态
    private boolean moveState   = false; // 手指是否移动
    private Dialog        mRecordDialog;
    private AudioRecorder mAudioRecorder;
    private MediaPlayer   mMediaPlayer;
    private Thread        mRecordThread;


    private Button mBtnDialogStop;

    private String eventTag = "";


    @Override
    protected void initTitle() {
        setBarTitle("录制音频");
    }

    @Override
    protected void callFinish() {
        try {
            stopRecord();
            if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
                mMediaPlayer.stop();
                playState = false;
            } else {
                playState = false;
            }
        } catch (Exception e) {
            if (BuildConfig.DEBUG) {
                e.printStackTrace();
            }
        }
        AppManager.getAppManager().finishActivity(RecordVoiceActivity.class);
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_record_voice;
    }


    @Override
    protected void getBundleArgs() {
        super.getBundleArgs();
        if (getIntent().getExtras() != null) {
            eventTag = getIntent().getStringExtra("tag");
        }
        eventTag = StringUtils.nullValue(eventTag, this.getClass().getName());
    }

    @Override
    protected void initViews() {
        super.initViews();
        mFileUrl = FileUtil.getFullAmrPath(IApplication.context());
    }

    @OnClick({R.id.btn_play})
    public void playAction(View view) {
        if (FileUtil.checkFileExistAndNotZero(mFileUrl)) {
            if (!playState) {
                mMediaPlayer = new MediaPlayer();
                try {
                    mMediaPlayer.setDataSource(mFileUrl);
                    mMediaPlayer.prepare();
                    btnPlay.setText("正在播放【点击可停止】");
                    playState = true;
                    mMediaPlayer.start();
                    //showVoiceDialog(0);
                    // 设置播放结束时监听
                    mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

                        @Override
                        public void onCompletion(MediaPlayer mp) {
                            if (playState) {
                                btnPlay.setText("播放");
                                playState = false;
                            }
                        }
                    });
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (IllegalStateException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            } else {
                if (mMediaPlayer.isPlaying()) {
                    mMediaPlayer.stop();
                    playState = false;
                } else {
                    playState = false;
                }
                btnPlay.setText("播放录音");
            }
        } else {
            mHUDUtil.showErrorTip("录制文件不存在，请重新录制");
        }
    }

    @OnClick({R.id.btn_record})
    public void recordAction(View view) {
        String[] perms = {Manifest.permission.RECORD_AUDIO,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE

        };
        checkPermission("App申请访问麦克风", new LemonPermissionListener() {
            @Override
            public void onPermissionGranted(int requestCode) {
                doRecord();
            }

            @Override
            public void onPermissionDenied(int requestCode, ArrayList<String> deniedPermissions) {
                showToast("请允许App访问麦克风设备后在执行改操作");
            }
        }, perms);

    }

    private void doRecord(){
        if (FileUtil.checkFileExistAndNotZero(mFileUrl)) {
            FileUtil.deleteFile(mFileUrl);
        }
        if (recordState != RECORD_ON) {
            mAudioRecorder = new AudioRecorder(mFileUrl);
            recordState = RECORD_ON;
            mAudioRecorder.start();
            recordTimeThread();
            showVoiceDialog(0);
        } else {
            showVoiceDialog(0);
        }
    }

    @OnClick({R.id.btn_submit, R.id.btn_cancel})
    public void submitOrCancelAction(View view) {
        if (view.getId() == R.id.btn_submit) {
            if (FileUtil.checkFileExistAndNotZero(mFileUrl)) {
                VoiceEvent event = new VoiceEvent();
                event.setTag(eventTag);
                event.setUrl(mFileUrl);
                AppService.getBus().post(event);
                callFinish();
            } else {
                mHUDUtil.showErrorTip("录制文件不存在，请重新录制");
            }
        } else if (view.getId() == R.id.btn_cancel) {
            callFinish();
        }
    }

    // 录音时显示Dialog
    private void showVoiceDialog(int flag) {
        if (mRecordDialog == null) {
            mRecordDialog = new Dialog(this, R.style.VoiceDialogStyle);
            mRecordDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            mRecordDialog.getWindow()
                         .setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
            mRecordDialog.setContentView(R.layout.view_record_dialog);
            mRecordDialog.setCanceledOnTouchOutside(false);
            mIvDialogRecVolume = (ImageView) mRecordDialog.findViewById(R.id.record_dialog_img);
            mTvDialogRecordTxt = (TextView) mRecordDialog.findViewById(R.id.record_dialog_txt);
            mBtnDialogStop = (Button) mRecordDialog.findViewById(R.id.btn_stop);
            mBtnDialogStop.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    stopRecord();
                }
            });
        }
        switch (flag) {
            case 1:
                mIvDialogRecVolume.setImageResource(R.drawable.record_cancel);
                mTvDialogRecordTxt.setText("点击关闭停止录音");
                break;

            default:
                mIvDialogRecVolume.setImageResource(R.drawable.record_animate_01);
                mTvDialogRecordTxt.setText("点击关闭停止录音");
                break;
        }
        mTvDialogRecordTxt.setTextSize(14);
        if (mRecordDialog.isShowing()) {
            mRecordDialog.dismiss();
        }
        mRecordDialog.show();
    }

    // 录音计时线程
    private void recordTimeThread() {
        mRecordThread = new Thread(recordThread);
        mRecordThread.start();
    }

    // 录音线程
    private Runnable recordThread = new Runnable() {

        @Override
        public void run() {
            recodeTime = 0.0f;
            while (recordState == RECORD_ON) {
                // 限制录音时长
                // if (recodeTime >= MAX_RECORD_TIME && MAX_RECORD_TIME != 0) {
                // imgHandle.sendEmptyMessage(0);
                // } else
                {
                    try {
                        Thread.sleep(150);
                        recodeTime += 0.15;
                        // 获取音量，更新dialog
                        if (!moveState) {
                            voiceValue = mAudioRecorder.getAmplitude();
                            recordHandler.sendEmptyMessage(1);
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    };

    public Handler recordHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            AudioRecorder.voiceImageChange(voiceValue, mIvDialogRecVolume);
        }
    };


    //停止录制
    private void stopRecord() {
        if (recordState == RECORD_ON) {
            recordState = RECORD_OFF;
            if (mRecordDialog.isShowing()) {
                mRecordDialog.dismiss();
            }
            mAudioRecorder.stop();
            mRecordThread.interrupt();
            voiceValue = 0.0;

            if (!moveState) {
                if (recodeTime < MIN_RECORD_TIME) {
                    mHUDUtil.showErrorTip("时间太短  录音失败");
                } else {
                    tvRecordTime.setText(((int) recodeTime) + "秒");
                    tvFileUrl.setText(mFileUrl);
                    btnPlay.setEnabled(true);
                    btnSubmit.setEnabled(true);
                }
            }
            moveState = false;
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        mAudioRecorder = null;
        mMediaPlayer = null;
        mRecordThread = null;
        try {
            if (mRecordDialog != null && mRecordDialog.isShowing()) {
                mRecordDialog.dismiss();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
